package com.dbq.fast.business.main;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.FireBaseUserPurchaseTrack;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.h5.H5ContainerActivity;
import com.dbq.fast.business.invite.InviteActivity;
import com.dbq.fast.business.login.NewLoginActivity;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.login.business.LoginBiz;
import com.dbq.fast.business.main.bean.HangQingInfo;
import com.dbq.fast.business.main.bean.VpnNode;
import com.dbq.fast.business.main.business.ExvBiz;
import com.dbq.fast.business.main.dialog.ConnectFailDialog;
import com.dbq.fast.business.main.dialog.TipDialog;
import com.dbq.fast.business.main.dialog.base.TipBaseDialog;
import com.dbq.fast.business.main.model.VpnModel;
import com.dbq.fast.business.me.MeActivity;
import com.dbq.fast.business.product.ProductTypeActivity;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.business.product.event.FaceBookUserPurchaseTrack;
import com.dbq.fast.business.setting.WfeeDialog;
import com.dbq.fast.business.ypage.YPageActivity;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.json.GsonT;
import com.dbq.fast.common.manager.DatabaseManager;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.glide.GlideApp;
import com.dbq.fast.util.PermissionUtil;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SpUtil;
import com.dbq.fast.util.SystemUtil;
import com.dbq.fast.util.WindowToastUtils;
import com.dbq.fast.view.CircleLoadingView;
import com.exv.sdk.coinex.mode.event.CurrencyEvent;
import com.exv.sdk.coinex.mode.event.LoginEvent;
import com.exv.sdk.coinex.mode.event.NeedLoginEvent;
import com.yiba.logutils.LogUtils;
import com.yiba.vpn.VPNServiceManager;
import com.yiba.vpn.core.LocalVpnService;
import com.yiba.vpn.core.VPNNode;
import com.yiba.vpn.protocal.DBQTestTimeDelay;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;
import com.yiba.vpn.utils.logger.LogUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.processors.FlowableProcessor;
import io.reactivex.schedulers.Schedulers;

import static com.dbq.fast.analysis.EventConstant.PARAM_C_NODE_E;
import static com.dbq.fast.analysis.EventConstant.PARAM_NET_OUT;
import static com.dbq.fast.analysis.EventConstant.PARAM_NEW_S_OUT;
import static com.dbq.fast.analysis.EventConstant.PARAM_NO_NET;
import static com.dbq.fast.analysis.EventConstant.PARAM_SS;
import static com.dbq.fast.analysis.EventConstant.PARAM_S_NO_AUTH;
import static com.dbq.fast.analysis.EventConstant.PARAM_S_OUT;
import static com.dbq.fast.business.main.dialog.TipDialog.ESTABLISH_VPN_FAILED;
import static com.dbq.fast.business.main.dialog.TipDialog.GET_VPN_TIME_OUT;
import static com.dbq.fast.business.main.dialog.TipDialog.NO_NETWORK;
import static com.dbq.fast.business.main.dialog.TipDialog.NO_VPN_SERVICE;
import static com.dbq.fast.business.main.dialog.TipDialog.SERVICE_OUT_DATE;
import static com.dbq.fast.util.SystemUtil.sleep;
import static com.yiba.vpn.core.LocalVpnService.STATUS_ESTABLISH_VPN_FAILED;

public class MainActivity extends BaseActivity {
    private final static int START_VPN_LOGIN_REQUEST_CODE = 100;
    public static final int START_VPN_SERVICE_REQUEST_CODE = 2333;
    private static final int GO_TO_SETTING_ACTIVITY = 101;
    private static int count = 0;

    @BindView(R.id.start_vpn)
    CircleLoadingView startVpnBtn;
    @BindView(R.id.disconnect_vpn)
    TextView disconnectBtn;
    @BindView(R.id.tariff_packages_name)
    TextView tariffPackageName;
    @BindView(R.id.tariff_packages_time_name)
    TextView tariffPackageTime;
    @BindView(R.id.title_meal_and_time)
    View tariffPackagesLabel;
    @BindView(R.id.mask)
    TextView maskBgTv;
    @BindView(R.id.invite_entrance)
    ImageView inviteEntranceView;
    @BindView(R.id.renew_tag)
    TextView renewTag;
    @BindView(R.id.trade1)
    TextView trade1;
    @BindView(R.id.trade2)
    TextView trade2;
    @BindView(R.id.trade3)
    TextView trade3;
    ImageView exvIcon;
    ImageView videoIcon;
    TextView exvTitle;
    TextView videoTitle;
    LinearLayout exvPartArea;
    TextView videoTip;
    @BindView(R.id.img_btn)
    ImageView btnImg;

    FlowableProcessor<String> startVpnListener;
    FlowableProcessor<String> loginOutListener;
    FlowableProcessor<LoginEvent> exvLoginListener;
//    FlowableProcessor<CurrencyEvent> hangQingListener;
    volatile VpnNode vpnNode;
    // 0 可以连接，1 正在连接，2 已经连接
    private static int vpnState;
    public static boolean showNewUserRewardDialog = false;
    private boolean hasPermission = true;
    public static boolean isNotificationOutDate = false; //是否收到通知过期
    private ExvBiz exvBiz;
//    private boolean isFirst = true;

    private LocalVpnService.onStatusChangedListener statusChangedListener = new LocalVpnService.onStatusChangedListener() {
        @Override
        public void onStatusChanged(String status, Boolean isRunning) {

            if (!isRunning && STATUS_ESTABLISH_VPN_FAILED.equals(status)) {
                offVpnConnecting();
                TipBaseDialog dialog = TipDialog.newInstance(ESTABLISH_VPN_FAILED);
                if (dialog != null && isResume) {
                    dialog.show(getSupportFragmentManager());
                }
                return;
            }

            if (!isRunning && vpnState == 0) {
                disConnectVpn();
                vpnState = 0;
                if (isResume) {
                    if (TipBaseDialog.isShowing("tip_dialog3")) return;
                    if (isNotificationOutDate) {
                        isNotificationOutDate = false;
                    } else {
                        ConnectFailDialog.show(getSupportFragmentManager()).setOnClickListener(v -> {
                            switch (v.getId()) {
                                case R.id.cancel:
                                    break;
                                case R.id.retry:
                                    checkIsLogin();

                                    break;
                            }
                        });
                    }
                }
            } else if (!isRunning && vpnState == 2) {//VPN stop connect
                offVpnConnecting();
            } else if (isRunning && vpnState == 1) {//VPNconneting->connected
                RxBus.get().post(Constants.RXBUS_START_VPN, Constants.RXBUS_START_VPN);
            }
        }

        @Override
        public void onLogReceived(String logString) {
            //com.yiba.logutils.save.impl.LogWriter.writeLog(VPNServiceManager.TAG, logString);
            LogUtils.getInstance().log(VPNServiceManager.TAG, logString);
        }
    };


    /**
     * 停止vpn连接动画
     */
    private void offVpnConnecting() {
        vpnState = 0;
        if (startVpnBtn != null) {
            startVpnBtn.setClickable(true);
            startVpnBtn.disconnect();
        }
        if (disconnectBtn != null) {
            disconnectBtn.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initPartView();
        initVpnListener();
        User.getInstance().init();
        disconnectBtn.setVisibility(View.GONE);
        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_START_APP);
        VpnModel.getProxyDomain();

        renewTag.setVisibility(View.GONE);

        PermissionUtil.verifyPermissions(MainActivity.this);
        updateLogic.autoTipUpdate();

        exvBiz = new ExvBiz(this);
        exvBiz.register();
//        exvBiz.accessMarketData();
    }

    private void initPartView() {
        exvIcon = findViewById(R.id.exv_icon);
        exvTitle = findViewById(R.id.exv);
        exvPartArea = findViewById(R.id.exv_part_area);
        videoIcon = findViewById(R.id.video_icon);
        videoTitle = findViewById(R.id.video);
        videoTip = findViewById(R.id.video_tip);

    }

    ObjectAnimator renewTagAnim;

    private void renewTagAnim() {
        if (renewTagAnim != null) {
            if (!renewTagAnim.isRunning()) {
                renewTagAnim.start();
            }
        } else {
            renewTagAnim = ObjectAnimator.ofFloat(renewTag, "rotation", -5, 5);
            renewTagAnim.setDuration(600);
            renewTagAnim.setRepeatMode(ObjectAnimator.REVERSE);
            renewTagAnim.setRepeatCount(ObjectAnimator.INFINITE);
            renewTagAnim.setInterpolator(new AccelerateInterpolator());
            renewTagAnim.start();
        }
    }

    private void initVpnListener() {
        startVpnListener = RxBus.get().register(Constants.RXBUS_START_VPN, String.class);
        startVpnListener.onBackpressureLatest()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    switch (s) {
                        case Constants.RXBUS_SERVER_DISABLED: //此处回调会一直刷
                            count++;
                            if (count == 4) {
                                uploadVPNTimeDelay(true);
                            }
                            break;
                        case Constants.RXBUS_START_VPN_NO_AUTHORIZATION:
                        case Constants.RXBUS_LOAD_VPN_ERROR:
                            vpnState = 0;
                            if (isResume) {
                                if (isNotificationOutDate) {
                                    isNotificationOutDate = false;
                                } else {
                                    if (isResume) {
                                        ConnectFailDialog.show(getSupportFragmentManager()).setOnClickListener(v -> {
                                            if (v.getId() == R.id.retry) {
                                                checkIsLogin();
                                            }
                                        });
                                    }
                                }
                            }
                            if (s == Constants.RXBUS_START_VPN_NO_AUTHORIZATION) {
                                Bundle bundle = new Bundle();
                                bundle.putString("open_faild_reason", PARAM_S_NO_AUTH);
                                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_FAILED, bundle);
                            } else {
                                Bundle bundle = new Bundle();
                                bundle.putString("open_faild_reason", PARAM_SS);
                                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_FAILED, bundle);
                            }
                            disConnectVpn();
                            offVpnConnecting();
                            updateTariffPackageInfo();
                            break;
                        case Constants.RXBUS_START_VPN:
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_SUCC);
                            connectedVpn(false);
                            updateTariffPackageInfo();
                            break;
                        case Constants.RXBUS_VPN_NODE_LOADED:
                            updateTariffPackageInfo();
                            checkIsExpired();
                            break;
                        case Constants.RXBUS_REFRESH_TOKEN_FAIL:
//                            Toast.makeText(App.getContext(), App.getContext().getString(R.string.login_token_invalid), Toast.LENGTH_SHORT).show();
                            WindowToastUtils.showShort(App.getContext(), App.getContext().getString(R.string.login_status_invalid));
                            updateTariffPackageInfo();
                            disConnectVpn();
                            offVpnConnecting();
                            reLogin();
                            break;
                        case Constants.RXBUS_OTHER_DEVICE_LOGIN:
                            Toast.makeText(App.getContext(), ""/*App.getContext().getString(R.string.login_on_other_device)*/, Toast.LENGTH_SHORT).show();
                            updateTariffPackageInfo();
                            disConnectVpn();
                            offVpnConnecting();
                            reLogin();
                            break;
                        case Constants.RXBUS_NO_SERVICE: //没有服务 code:-1004
                            Bundle bundle = new Bundle();
                            bundle.putString("open_faild_reason", PARAM_NEW_S_OUT);
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_FAILED, bundle);
                            if (isResume) {
                                TipBaseDialog dialog = TipDialog.newInstance(NO_VPN_SERVICE);
                                if (dialog != null) {
                                    dialog.show(getSupportFragmentManager());
                                }
                            }
                            updateTariffPackageInfo();
                            offVpnConnecting();
                            disConnectVpn();
                            break;
                        case Constants.RXBUS_SERVICE_OUT_DATE: //服务过期 code:-1005
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("open_faild_reason", PARAM_S_OUT);
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_FAILED, bundle1);
                            if (isResume) {
                                TipBaseDialog dialog = TipDialog.newInstance(SERVICE_OUT_DATE);
                                if (dialog != null) {
                                    dialog.show(getSupportFragmentManager())
                                            .setOnClickListener(new TipBaseDialog.IOnClickListener() {
                                                @Override
                                                public void operate1Click() {
                                                    YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_S_OUT_CANCEL);
                                                }

                                                @Override
                                                public void operate2Click() {
                                                    YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_S_OUT_BUY_NOW);
                                                    goProductPage();
                                                }
                                            });
                                }
                                onResume();
                            }
                            new Thread(() -> User.getInstance().loadVpnNode()).start();
                            offVpnConnecting();
                            disConnectVpn();
                            break;
                        case Constants.RXBUS_CREATE_NODE_EXCEPTION: //创建节点失败 code:-1007
                            Bundle bundle3 = new Bundle();
                            bundle3.putString("open_faild_reason", PARAM_C_NODE_E);
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_FAILED, bundle3);
                            break;
                        case Constants.RXBUS_GET_VPN_TIME_OUT:
                            Bundle bundle2 = new Bundle();
                            bundle2.putString("open_faild_reason", PARAM_NET_OUT);
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_FAILED, bundle2);
                            if (isResume) {
                                TipBaseDialog dialog = TipDialog.newInstance(GET_VPN_TIME_OUT);
                                if (dialog != null) {
                                    dialog.show(getSupportFragmentManager())
                                            .setOnClickListener(new TipBaseDialog.IOnClickListener() {
                                                @Override
                                                public void operate1Click() {
                                                    YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_NET_OUT_CANCEL);
                                                }

                                                @Override
                                                public void operate2Click() {
                                                    YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_NET_OUT_RETRY);
                                                    startVpn();
                                                }
                                            });
                                }
                            }
                            offVpnConnecting();
                            disConnectVpn();
                            break;
                        case Constants.OPEN_VPN:
                            startVpn();
                            break;
                        case Constants.RXBUS_LOGOUT:
                            reLogin();
                            break;
                        case Constants.RXBUS_GO_WFEE:
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_EXV);

                            if (exvBiz != null) {
                                logining = true;
                                exvBiz.login();
                                ProgressDialogUtil.showProgress(this, "", getString(R.string.tip_loading));
                            }
                            break;
                    }
                });

        loginOutListener = RxBus.get().register(Constants.RXBUS_LOGIN_OUT, String.class);
        loginOutListener.onBackpressureLatest()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    LogUtil.e("退出登录,断开 VPN");
                    disConnectVpn();
                    tariffPackageName.setText("");
                    tariffPackageTime.setText("");
                });

//        hangQingListener = RxBus.get().register(Constants.RXBUS_ACCESS_HANGQING, CurrencyEvent.class);
//        hangQingListener.sample(5, TimeUnit.SECONDS)
//                .compose(new CommonTransformer<>())
//                .subscribe(event -> {
////                    Log.e("yc_", "event.data:" + event.data);
//                    HangQingInfo hangQingInfo = GsonT.parseJson(event.data, HangQingInfo.class);
//                    if ("SUCCESS".equals(hangQingInfo.getResponse_code())) {
//                        List<HangQingInfo.TransPairMarketsBean> transPairMarkets = hangQingInfo.getTrans_pair_markets();
//                        for (HangQingInfo.TransPairMarketsBean t : transPairMarkets) {
//                            if ("BTC/USDT".equals(t.getTrans_pair_desc())) {
//                                if (t.getUp_or_down() >= 0) {
//                                    trade1.setText("+" + t.getFluctuation_ratio() + "%");
//                                    trade1.setTextColor(Color.parseColor("#1AAF66"));
//                                } else {
//                                    trade1.setText("-" + t.getFluctuation_ratio() + "%");
//                                    trade1.setTextColor(App.getContext().getResources().getColor(android.R.color.holo_red_light));
//                                }
//                            } else if ("ETH/USDT".equals(t.getTrans_pair_desc())) {
//                                if (t.getUp_or_down() >= 0) {
//                                    trade2.setText("+" + t.getFluctuation_ratio() + "%");
//                                    trade2.setTextColor(Color.parseColor("#1AAF66"));
//                                } else {
//                                    trade2.setText("-" + t.getFluctuation_ratio() + "%");
//                                    trade2.setTextColor(App.getContext().getResources().getColor(android.R.color.holo_red_light));
//                                }
//                            } else if ("WFEE/USDT".equals(t.getTrans_pair_desc())) {
//                                if (t.getUp_or_down() >= 0) {
//                                    trade3.setText("+" + t.getFluctuation_ratio() + "%");
//                                    trade3.setTextColor(Color.parseColor("#1AAF66"));
//                                } else {
//                                    trade3.setText("-" + t.getFluctuation_ratio() + "%");
//                                    trade3.setTextColor(App.getContext().getResources().getColor(android.R.color.holo_red_light));
//                                }
//                            }
//                        }
//                    }
//                });
        exvLoginListener = RxBus.get().register(Constants.RXBUS_EXV_LOGIN, LoginEvent.class);
        exvLoginListener.compose(new CommonTransformer<>())
                .subscribe(event -> {
                    if (event.data.contains("SUCCESS")) {
                        Intent intent = new Intent();
                        intent.setAction("com.exv.coinex");
                        startActivity(intent);
                    } else {
                        Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_loading_fail), Toast.LENGTH_SHORT).show();
                    }
                });

        LocalVpnService.addOnStatusChangedListener(statusChangedListener);
    }

    private void checkIsExpired() {
        if (User.getInstance().getUserSetMealAvailableTime() >= 10) {
            renewTag.setVisibility(View.GONE);
        } else {
            if (User.getInstance().getPurchaseState() != 2) {
                renewTag.setVisibility(View.VISIBLE);
            }
            renewTagAnim();
        }
    }

    private void reLogin() {
        if (!isFinishing()) {
            LoginBiz loginBiz = new LoginBiz(MainActivity.this);
            loginBiz.logOut();

            if (updateLogic != null) {
                updateLogic.onDestory();
            }

            Intent loginIntent = new Intent(MainActivity.this, MainActivity.class);
            startActivity(loginIntent);
            Intent intent = new Intent(MainActivity.this, NewLoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);


        }
    }

    /**
     * 更新套餐信息
     */
    @SuppressLint("StringFormatInvalid")
    private void updateTariffPackageInfo() {
        if (tariffPackageName == null ||
                tariffPackagesLabel == null ||
                tariffPackageTime == null) return;

        if (User.getInstance().isLogin()) {
            tariffPackagesLabel.setVisibility(View.VISIBLE);
            tariffPackageTime.setVisibility(View.VISIBLE);
        } else {
            tariffPackageName.setText("----");
            tariffPackageTime.setText("----");
            return;
        }
        tariffPackageName.setText(User.getInstance().getUserServiceName());
        int availableTime = User.getInstance().getUserSetMealAvailableTime();
        tariffPackageTime.setText(App.getContext().getString(R.string.how_much_days, "" + availableTime));
        if (availableTime == -1) {
            tariffPackageName.setText("----");
            tariffPackageTime.setText("----");
        } else if (availableTime <= 0) {
            tariffPackageTime.setText(getString(R.string.outdate));
            isNotificationOutDate = true;
            disConnectVpn();
            offVpnConnecting();
        } else if (availableTime <= 1) {
            tariffPackageTime.setText(App.getContext().getString(R.string.how_much_day, "<1"));
            if (User.getInstance().isLess30Minute()) {
                tariffPackageTime.setText(App.getContext().getString(R.string.how_much_minute, "<30"));
            }
        }
    }

    @OnClick({R.id.my_account, R.id.buy_vpn, //
            R.id.start_vpn, R.id.img_btn,//
            R.id.disconnect_vpn, R.id.invite_entrance,//
            R.id.exv_area, R.id.video_area})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.my_account:
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_ME);
                startActivityForResult(new Intent(this, MeActivity.class), GO_TO_SETTING_ACTIVITY);
                break;
            case R.id.buy_vpn:
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_MEAL);
                FireBaseUserPurchaseTrack.servicePage(App.getContext());
                FaceBookUserPurchaseTrack.servicePage();
                goProductPage();
                break;
            case R.id.start_vpn:
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_TO_OPEN);
                if (!SystemUtil.isNetworkAvailable(App.getContext())) {
                    Bundle bundle = new Bundle();
                    bundle.putString("open_faild_reason", PARAM_NO_NET);
                    YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_FAILED, bundle);
                }
                startVpn();
                break;
            case R.id.disconnect_vpn:
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_TO_CLOSE);
                disConnectVpn();
                break;
            case R.id.invite_entrance:
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_INVITE_ENTRANCE);
                startActivity(new Intent(this, InviteActivity.class));
                break;
            case R.id.exv_area:
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CLICK_EXV);
                if (this != null && !isFinishing()) {
                    ProgressDialogUtil.showProgress(this, "", getString(R.string.tip_loading), true);
                }
                exvBiz.login();
                break;
            case R.id.video_area:
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_VIDEO);
                startActivity(new Intent(MainActivity.this, YPageActivity.class));
                break;
            case R.id.img_btn:
                go2Wfee();
                break;
        }
    }

    private void go2Wfee() {
        if (wfeeBundle != null) {
            Intent intent = new Intent(MainActivity.this,//
                    H5ContainerActivity.class);
            intent.putExtras(wfeeBundle);
            startActivity(intent);
        }

    }

    private void openWfee() {
        WfeeDialog.show(getSupportFragmentManager(),//
                WfeeDialog.UPDATE_VERSION)//
                .setWfeeListener(new WfeeDialog.OnWfeeListener() {
                    @Override
                    public void nextPage() {
                        go2Wfee();
                    }

                    @Override
                    public void cancel() {

                    }
                });
    }

    private Bundle wfeeBundle;
    boolean logining;

    @Subscribe
    public void onEvent(LoginEvent event) {
        //登录数据
//        RxBus.get().post(Constants.RXBUS_EXV_LOGIN, event);
        Intent intent = new Intent();
        intent.setAction("com.exv.coinex");
        MainActivity.this.startActivity(intent);

        ProgressDialogUtil.hideProgress();
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onEvent(CurrencyEvent event) {
//        RxBus.get().post(Constants.RXBUS_ACCESS_HANGQING, event);
    }

    @Subscribe
    public void onEvent(NeedLoginEvent event) {
        Log.e("yc_", "----relogin----~~~~!!!!");
        reLogin();
    }

    private void goProductPage() {
        startActivityForResult(new Intent(MainActivity.this, ProductTypeActivity.class), 3000);
    }

    private void startVpn() {
        boolean isNetAvail = SystemUtil.isNetworkAvailable(App.getContext());
        if (isNetAvail) {
            checkIsLogin();
        } else {
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_FAILED_NO_NET);
            if (isResume) {
                TipBaseDialog dialog = TipDialog.newInstance(NO_NETWORK);
                if (dialog != null) {
                    dialog.show(getSupportFragmentManager());
                }
            }
        }
    }

    private void disConnectVpn() {
        //停止VPN服务
        if (LocalVpnService.IsRunning) {
            LocalVpnService.IsRunning = false;
        }
        //停止VPN的端口检测
        if (DBQTestTimeDelay.IsRunning) {
            DBQTestTimeDelay.IsRunning = false;
        }

    }

    private void connectedVpn(boolean isFromResume) {
        startVpnBtn.setClickable(false);
        startVpnBtn.completed();
        disconnectBtn.setVisibility(View.VISIBLE);
        vpnState = 2;
        if (isResume && !SpUtil.getBoolean(Constants.IS_FIRST_CONNECTED)) {
//            PopupWindowUtil.firstConnectTips(getApplicationContext(), findViewById(R.id.custom_server));
            SpUtil.setBoolean(Constants.IS_FIRST_CONNECTED, true);
        }

        if (!isFromResume && vpnNode != null && vpnNode.getIsFirstConnect() == 1) {
//            FreeDaysFragment.showFreeDaysDialog(getSupportFragmentManager(), getString(R.string.free_days_title, 2));
        }

    }


    @Override
    protected void onResume() {
        if (!User.getInstance().isLogin()) {
            disConnectVpn();
        } else {
            User.getInstance().setVpnNode(null);
            new Thread(() -> {
                VpnNode vpnNode = User.getInstance().loadVpnNode();
                if (vpnNode == null) return;
                //TODO 是否显示显示空投入口按钮
                runOnUiThread(() -> {
                    if (wfeeBundle == null) {
                        wfeeBundle = new Bundle();
                        wfeeBundle.putInt("which", H5ContainerActivity.COMMON);
                        wfeeBundle.putString("title", "WFee交易所空投");
                        wfeeBundle.putString("url", vpnNode.getAirDropUrl());
                        wfeeBundle.putString("content", vpnNode.getAirDropBody());
                        btnImg.setVisibility(vpnNode.isShow() ? View.VISIBLE : View.GONE);
                        if (isResume && !isFinishing()) {
                            GlideApp.with(this).asGif().load(R.drawable.kt_gif).into(btnImg);
                        }
                    }
                });

            }).start();
        }
        if (LocalVpnService.IsRunning) {
            connectedVpn(true);
        } else if (hasPermission && isNotificationOutDate) {
            offVpnConnecting();
        }
        if (vpnState == 1) {
            startVpnBtn.setClickable(false);
            startVpnBtn.startAnimation();
        }
        updateTariffPackageInfo();
//        if (isFirst) {
//            if (exvBiz != null) {
//                exvBiz.offMarketData();
//            }
//            isFirst = false;
//        }

        super.onResume();
    }

    /**
     * 启动 VPN 服务
     */
    private void checkIsLogin() {
        startVpnBtn.setClickable(false);
        if (User.getInstance().isLogin()) {
            startVpnBtn.startAnimation();
            vpnState = 1;
            new Thread(() -> {
                sleep(1000);
                try {
                    if (App.getContext() == null) return;
                    vpnNode = new VpnModel().getVpnConfig(User.getInstance().getToken(), User.getInstance().getAccount());
                    if (vpnNode != null) {
                        Intent intent = LocalVpnService.prepare(App.getContext());
                        if (intent == null) {
                            hasPermission = true;
                            startVPNService(vpnNode, User.getInstance().getProxyDomain().proxy_domain);
                        } else {
                            hasPermission = false;
                            startActivityForResult(intent, START_VPN_SERVICE_REQUEST_CODE);
                        }
                        User.getInstance().setVpnNode(vpnNode);
                        if (vpnNode != null) {
                            User.getInstance().setUserServiceName(vpnNode.getUserServiceName());
                            User.getInstance().setUserSetMealAvailableTime(vpnNode.getUserSetMealAvailableTime());
                        }
                        uploadVPNTimeDelay(false);
                    }
                } catch (Exception e) {
                }
            }).start();
        } else {
            Intent intent = new Intent(this, NewLoginActivity.class);
            intent.putExtra("goLogin", true);
            startActivityForResult(intent, START_VPN_LOGIN_REQUEST_CODE);
        }
    }

    /**
     * 上传VPN时延超时检测
     *
     * @param isServerDisabaled false：服务器被墙
     */
    private void uploadVPNTimeDelay(boolean isServerDisabaled) {
        if (vpnNode == null) return;
        HashMap params = new HashMap();
        CustomProfile profileNew = DatabaseManager.getInstance().queryProfile();
        params.put("account", profileNew.getAccount());
        params.put("phone", Build.MODEL);
        params.put("os", "Android" + profileNew.getOsVer());
        params.put("version", profileNew.getAppVer());
        params.put("service", User.getInstance().getUserServiceName());//套餐信息
        params.put("node_service_host", vpnNode == null ? "" : vpnNode.getServer());
        params.put("server_host_port", vpnNode == null ? "" : vpnNode.getServer_port());
        params.put("androidID", SystemUtil.getAndroidId(this));
        params.put("country", SystemUtil.getCountry(this));
        params.put("isWifiEnable", SystemUtil.isWifiEnable(this) ? 1 : 0);//判断是否WIFI 上网
        params.put("operatorinfo", SystemUtil.getNetworkOperatorInfo(this));
        params.put("isServerDisabaledBeginTime", new Date().getTime());
        params.put("isServerDisabaled", isServerDisabaled ? 1 : 0);
        params.put("delay", DBQTestTimeDelay.aPartDealy);
        HttpManager.getInstance().getHttpService()
                .uploadVPNTimeDelay(User.getInstance().getToken(), params)
                .compose(new CommonTransformer<>())
                .subscribe(httpResult -> {
                }, throwable -> {
                });
    }

    /**
     * 开启VPN服务
     **/
    private void startVPNService(VpnNode vpnNode, List<String> proxyDomain) {
        if (vpnNode != null && vpnNode.getUserSetMealAvailableTime() > 0) {
            VPNNode vpnNode_lib = new VPNNode();
            VPNNode.ConfigBean configBean = new VPNNode.ConfigBean();
            vpnNode_lib.setMethod(vpnNode.getMethod());
            vpnNode_lib.setPassword(vpnNode.getPassword());
            vpnNode_lib.setServer(vpnNode.getServer());
            vpnNode_lib.setServer_port(vpnNode.getServer_port());
            configBean.setDns(vpnNode.getDns());
            configBean.setIp(vpnNode.getIp());
            configBean.setProxy_domain(proxyDomain);
            vpnNode_lib.setConfig(configBean);
            VPNServiceManager.getInstance().setVPNConfig(vpnNode_lib);
            Intent intent = new Intent(this, LocalVpnService.class);
            intent.putExtra("server", vpnNode.getServer());
            intent.putExtra("port", Integer.parseInt(vpnNode.getServer_port()));
            startService(intent);
        } else {
            RxBus.get().post(Constants.RXBUS_START_VPN, Constants.RXBUS_LOAD_VPN_ERROR);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            if (updateLogic != null) {
                updateLogic.onDestory();
            }
        }
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(Constants.RXBUS_START_VPN, startVpnListener);
        RxBus.get().unregister(Constants.RXBUS_LOGIN_OUT, loginOutListener);
//        RxBus.get().unregister(Constants.RXBUS_ACCESS_HANGQING, hangQingListener);
        LocalVpnService.removeOnStatusChangedListener(statusChangedListener);
        ProgressDialogUtil.hideProgress();
        if (renewTagAnim != null) {
            if (renewTagAnim.isRunning()) {
                renewTagAnim.cancel();
            }
        }

        if (exvBiz != null) {
//            exvBiz.offMarketData();
            exvBiz.unregister();
        }
        super.onDestroy();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == START_VPN_LOGIN_REQUEST_CODE || requestCode == GO_TO_SETTING_ACTIVITY) {//只有触发登陆请求，才会返回到这里
            if (resultCode == RESULT_OK) {
                User.getInstance().init();
                if (User.getInstance().isNewUser()) {
                    showNewUserRewardDialog = true;
                } else {
                    checkIsLogin();
                }

            } else {
                if (!User.getInstance().isLogin()) {
                    startVpnBtn.setClickable(true);
                }
            }
        } else if (requestCode == START_VPN_SERVICE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                startVPNService(vpnNode, User.getInstance().getProxyDomain().proxy_domain);
            } else {
                RxBus.get().post(Constants.RXBUS_START_VPN, Constants.RXBUS_START_VPN_NO_AUTHORIZATION);
                Toast.makeText(App.getContext(), App.getContext().getText(R.string.showtips), Toast.LENGTH_LONG).show();
            }
        }
    }

//    @Override
//    protected void onResumeFragments() {
//        super.onResumeFragments();
//        if (showNewUserRewardDialog) {
//            showNewUserRewardDialog = false;
//            if (isResume) {
//                NewUserRewardDialog.show(getSupportFragmentManager()).setOnClickListener(v -> {
//                    checkIsLogin();
//                });
//            }
//        }
//    }


    @Override
    protected void lastVersion() {
        super.lastVersion();
        boolean isLastVer = SpUtil.getBoolean("isFirstOpenWfee", true);
        if (isLastVer) {
            SpUtil.setBoolean("isFirstOpenWfee", false);
            runOnUiThread(() -> openWfee());
        }
    }
}
